package com.apimarket.util.net;

import com.apimarket.enums.NetContextEnum;
import com.apimarket.exception.NetContextException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

public class PatchJsonNetContext extends NetContext {
    private CloseableHttpClient client;

    private HttpPatch httpPatch;

    static final int SUCCESS_CODE = 200;

    public PatchJsonNetContext(String url, Map<String, Object> params) {
        super(url, params);
        client = HttpClients.createDefault();
        httpPatch = new HttpPatch(getUrl());
    }

    CloseableHttpResponse getResponse() throws IOException {
        setJsonStyle(httpPatch);
        return client.execute(httpPatch);
    }

    @Override
    public JsonNode getResultJson() throws IOException, URISyntaxException {
        try (CloseableHttpResponse response = getResponse()) {
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String jsonStr = getJsonStr(entity);
            EntityUtils.consume(entity);
            if (statusCode == SUCCESS_CODE) {
                return new ObjectMapper().readTree(jsonStr);
            } else {
                logger.error(jsonStr);
                throw new NetContextException(NetContextEnum.UPDATE_ERROR);
            }

        }
    }
}
